// pages/buy_step1/buy_step1.js
var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
var key = "";
Page({ 
  data: {},
  onLoad: function (options) {  
//console.log(options);
    var hide = "hide";
    var that = this;
    var cart_id = "";
    var ifcart= "";
    var address_id = "";
    if (options.ifcart==1){
      
      cart_id = wx.getStorageSync('cart_listArr');      
      ifcart = options.ifcart;

    }else{

      ifcart = 0;
      cart_id = options.goodsId+"|"+options.buynum;
      that.setData({
        buynum: options.buynum,
        goodsId: options.goodsId
      });

    }      
    key = options.key;
    address_id = options.address_id?options.address_id:0;
     wx.request({
       url: ApiUrl + '/index.php?act=member_buy&op=buy_step1',
       data: {
         'key': key,'cart_id': cart_id, 'ifcart': ifcart,'address_id':address_id 
      },
       header: {
         'content-type': 'application/x-www-form-urlencoded'
       },
       method:'post',
       success:function(result){
         
          that.setData({           
              store_cart_list: result.data.datas.store_cart_list,
              address_info: result.data.datas.address_info,           
              content: result.data.datas.address_api.content ? result.data.datas.address_api.content:"",
              order_amount: result.data.datas.order_amount,
              store_final_total_list: result.data.datas.store_final_total_list,
              vat_hash: result.data.datas.vat_hash,
              offpay_hash: result.data.datas.address_api.offpay_hash,
              offpay_hash_batch:result.data.datas.address_api.offpay_hash_batch,
              ifcart: ifcart,
              inv_infoContent:"不需要发票",
              inpcon: 'none',
              key:key              
          }); 

          wx.request({
              url: ApiUrl + '/index.php?act=area&op=area_list',
              data: { 'area_id': options.ASID },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (result) {

                that.setData({
                  index: 1,
                  area_list: result.data.datas.area_list,
                  showOrNo: 'hidden',
                  county: "区县",
                  city: "城市",
                  area: "省份",
                });
              }
          });
          
          if (result.data.datas.address_info.length==0) {
              hide = 'left';            
          }              
          that.setData({            
            showNo: 'hide',
            selectDress: hide,
            hides:'hide' ,
            maskbg:'hide'        
          }); 

       }
     });
  },
  //新增收货地址
  addAdress:function(){  

     var that = this;
     that.setData({
       showNo:'left'
     });

  },
  changeinvoice:function(){

    var that = this;
    that.setData({
      hides: 'left',
      noInvoiceSel:'sel',
      invoiceSel:'',
      maskbg:'showmask'
    });

  },
  hideInvoice:function(){

    var that = this;    
    that.setData({
      maskbg: 'hide',
      hides: "hide",
      noInvoiceSel: 'sel',
      invoiceSel: '',
      inpcon:'none',
      invoice_content_list:'',
      inv_infoContent:'不需要发票'
    });

  },
  radioChange:function(e){
   
    var invId = e.detail.value;
    var that = this;
    var key = e.currentTarget.dataset.key;
    var inv_infoConten = "";
    var hides = "";
    var invoice_add = "";
    var maskbg = "";
    var inpcon = "";
    var inv_infoContent = "";
    for (var i = 0; i < that.data.invoice_list.length;i++){
      if (invId == that.data.invoice_list[i]['inv_id']){
       
        inv_infoContent = that.data.invoice_list[i]['inv_title'] + that.data.invoice_list[i]['inv_t_code'] + that.data.invoice_list[i]['inv_content']
      }  
    }    
     
    wx.setStorageSync("invoice_id", invId);

    wx.request({
      url: ApiUrl + '/index.php?act=member_invoice&op=invoice_content_list',
      data: { key: key },
      header:{'content-type': 'application/x-www-form-urlencoded'},
      method:"post",
      success:function(res){
       
          if (invId == 0) {  
            invoice_add = "block";  
            inpcon = "block";
            maskbg = "left";
            hides = "left";
          } else {
            hides="hide";  
            maskbg = "hide";  
            invoice_add = "none";  
         } 
          that.setData({
            hides: hides,
            maskbg: maskbg,
            invoice_add: invoice_add,
            inpcon: inpcon,
            invoice_content_list: res.data.datas.invoice_content_list,
            inv_infoContent: inv_infoContent         
          });  
      }
    })

  },
  closeInvo:function(){
      this.setData({
        hides:"hide",
      });
  },
  invoformSubmit:function(e){
    var param = {};
    var that = this;
    var inv_id = "";
    var inv_infoContent = "";
    param.inv_t_code = e.detail.value.inv_t_code;
    param.inv_title = e.detail.value.inv_title;
    param.inv_title_select = wx.getStorageSync("inv_title_select");
    param.inv_content = wx.getStorageSync("inv_content");
    param.key = wx.getStorageSync("key");
     
    wx.request({
      url: ApiUrl + '/index.php?act=member_invoice&op=invoice_add',
      data: param,
      header: {'content-type': 'application/x-www-form-urlencoded'},
      method:"post",
      success:function(res){        
        var inv_id = res.data.datas.inv_id;         
        
        inv_infoContent = param.inv_title + param.inv_t_code + param.inv_content;               
        that.setData({
          hides: "hide",
          maskbg: 'hide',
          invoice_add: 'none',   
          inv_infoContent: inv_infoContent,
          inpcon:'none'
        });
        wx.setStorageSync("invoice_id", inv_id);     

      }
    })
     
  },
  delinvoice:function(e){
   
    var that = this;
    var inv_id = e.currentTarget.dataset.inv_id;
    key = wx.getStorageSync("key");
    
    wx.request({
      url: ApiUrl + '/index.php?act=member_invoice&op=invoice_del',
      data: {'key':key,'inv_id':inv_id },
      header: { 'content-type': 'application/x-www-form-urlencoded'},
      method:"post",
      success:function(res){                
          that.showInvoice();
      }  
    });

  },
  showInvoice: function (option) {
      var that = this;
      key = wx.getStorageSync('key');   
      
      wx.request({
        url: ApiUrl+'/index.php?act=member_invoice&op=invoice_list',
        data:{'key':key},
        header:{'content-type': 'application/x-www-form-urlencoded'},
        method:'post',
        success:function(result){     
            that.setData({
              invoice_list: result.data.datas.invoice_list,
              noInvoiceSel: "",
              invoiceSel: "sel",
              inpcon: "block",
              invoice_add:"none",
              invTcode: "none"
            });
        } 
      });
   
  },
  flashDiv:function(){

     var that = this;
     that.setData({
       maskbg:'hide',
       hides:'hide'
     });

  },
  EventHandle:function(e){
    
    if (e.detail.value =="company"){
      this.setData({
        invTcode:""
      });
    }else{
      this.setData({
        invTcode: "none"
      });
    }
    wx.setStorageSync("inv_title_select", e.detail.value);
  },
  bindPickerChange: function (e){
    
      var i = e.detail.value;
      this.setData({
        index: i
      });  
      wx.setStorageSync("inv_content", this.data.invoice_content_list[i]);

  },
  // 地址列表
  adressList:function(info){   
     
      var that = this; 
      key = info.currentTarget.dataset.key;
   
      wx.request({
        url: ApiUrl + "/index.php?act=member_address&op=address_list",
        data:{'key':key},
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'post',
        success:function(result){
          
            if (result.data.datas.address_list.length < 1) {
              return false;
            }
            var data = result.data.datas;            
            that.setData({
              oldaddress_id: info.currentTarget.dataset.address_id,
              selectDress:'left',
              address_list: result.data.datas.address_list,
              ifcart: info.currentTarget.dataset.ifcart,
              goodsId: info.currentTarget.dataset.goodsid,
              buynum: info.currentTarget.dataset.buynum,
              maskbg: 'showmask'
            });

        }
      })
  },
  changeAddressList:function( e ){

     var str = "";
     if (e.currentTarget.dataset.ifcart){
       str += "&ifcart=" + e.currentTarget.dataset.ifcart;
     }
     if (e.currentTarget.dataset.buynum) {
       str += "&buynum=" + e.currentTarget.dataset.buynum;
     }
     if (e.currentTarget.dataset.address_id) {
       str += "&address_id=" + e.currentTarget.dataset.address_id;
     } 
     if (e.currentTarget.dataset.goodsid) {
       str += "&goodsId=" + e.currentTarget.dataset.goodsid;
    } 
    key = e.currentTarget.dataset.key;
     
   wx.redirectTo({
     url: "/pages/buy_step1/buy_step1?key="+key+str,
   })
  },
  actionSheetTap:function(e){
  
        var that = this;    
        var area_id = '';          
        var city_list = '';
        var county_list = '';
        var area = '';
        var city = '';
        var county = '';    

        if (e.currentTarget.dataset.area_id) {     
          area = that.data.area_list[e.detail.value]['area_name'];
          area_id = that.data.area_list[e.detail.value]['area_id'];
        } else if (e.currentTarget.dataset.city_id){      
          city = that.data.city_list[e.detail.value]['area_name'];
          area_id = that.data.city_list[e.detail.value]['area_id'];
        } else if (e.currentTarget.dataset.county_id){            
          county = that.data.county_list[e.detail.value]['area_name'];         
         
        }
        if(area_id){
              wx.request({
                url: ApiUrl + '/index.php?act=area&op=area_list',
                data: {'area_id':area_id},
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: function(result){

                  if (e.currentTarget.dataset.area_id) {

                      city_list = result.data.datas.area_list;
                      that.setData({
                        area_id: area_id,
                        area:area,              
                        city_list: city_list,
                        county: county,                       
                      }); 

                  } else if (e.currentTarget.dataset.city_id) {

                      county_list = result.data.datas.area_list;                               
                      that.setData({
                        city_id: area_id,
                        city: city,                
                        county_list: county_list,
                        county: county,
                      });

                  } 
                }
              })
        }
  },
  formSubmit: function (e) {

      var that = this;      
      var is_default = 0;     
      var true_name = e.detail.value.true_name;
      var mob_phone = e.detail.value.mob_phone;
      var address = e.detail.value.vaddress; 
      var area_id = e.detail.value.area_id;
      var city_id = e.detail.value.city_id; 
      var area_info = e.detail.value.varea_info;      
      key = e.detail.value.key;

      wx.request({
        url: ApiUrl + "/index.php?act=member_address&op=address_add",
        data: { 
                'is_default': is_default,
                'key': key,
                'true_name': true_name,
                'mob_phone': mob_phone,
                'address': address,
                'area_id': area_id,
                'city_id': city_id,
                'area_info':area_info,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'post',
        success:function(result){
            wx.request({
              url: ApiUrl + "/index.php?act=member_address&op=address_info",
              data: {
                'address_id': result.data.datas.address_id,
                'key':key,
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              method: 'post',
              success: function (results) {
                    that.setData({
                      address_info: results.data.datas.address_info,
                      showNo: 'hide',
                      selectDress:'hide',
                      maskbg:'hide'
                    });
                  
              }
            });
        }
      });   
  },
  changeAddress:function(){   
      var that = this;
      that.setData({
        selectDress: '',
      });
  },
  submitOrders:function(e){
    
    var that = this;     
    var data = that.data;  
    var ifcart = data.ifcart;
    var pay_name = 'online';
    var invoice_id = wx.getStorageSync("invoice_id");
    var voucher = '';
    var pd_pay = 0;
    var rcb_pay = 0;
    var rpt = '';
    var pay_message = '';
    var fcode = '';
    var cart_id = "";
    var address_ids = data.address_info.address_id;   
   
    var offpay_hash_batch = data.offpay_hash_batch;
    var offpay_hash = data.offpay_hash;
    var vat_hash = data.vat_hash;
    var password="";    
    var buyArray = "";
    var cartArray = "";
    var newList = "";     

    if (ifcart == 1) {
      cart_id = wx.getStorageSync('cart_listArr');
      ifcart = ifcart;
    } else {
      cart_id = data.goodsId + "|" + data.buynum;
      ifcart = 0;
    }  
    
    key = e.currentTarget.dataset.key;
    wx.request({
      url: ApiUrl + '/index.php?act=member_buy&op=buy_step2',
      data:{
          'key':key,
          'ifcart':ifcart,
          'pay_name': pay_name,
          'invoice_id': invoice_id,
          'pd_pay': pd_pay,
          'rcb_pay': rcb_pay,
          'rpt': rpt,
          'pay_message': pay_message,
          'cart_id': cart_id,
          'address_id': address_ids,
          'offpay_hash_batch': offpay_hash_batch,
          'offpay_hash': offpay_hash,
          'vat_hash': vat_hash,
          'password': password,
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'
      },
      method:'POST',
      success:function(results){  
        
          if(results.data.code==400){
            wx.showModal({
              title: '',
              content: results.data.datas.error,
            })
          }
            
          that.setData({
            pay_sn: results.data.datas.pay_sn
          });
          if(ifcart==1){

              buyArray = wx.getStorageSync("cart_listArr");
              cartArray = wx.getStorageSync("cart_list");
              newList = cartArray.replace(buyArray, "");          
              wx.setStorageSync("cart_list", newList);
              wx.removeStorageSync('buyNums');
              wx.removeStorageSync('goods_cart');
              wx.removeStorageSync('cart_count');
              wx.removeStorageSync('cart_listArr');
          } 
          
          wx.request({
              url: ApiUrl + '/index.php?act=member_buy&op=pay',
              data: {'pay_sn': results.data.datas.pay_sn,'key':key },
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              method: 'POST',
              success: function (res) {
               
                that.setData({
                  pay_info: res.data.datas.pay_info,                
                }); 

              },
              
          });

      }
    })
     
  },
  topay:function(option){  
   
    var key = option.currentTarget.dataset.key;
    var pay_sn = option.currentTarget.dataset.pay_sn;
    var openid = wx.getStorageSync('openid');
   
    wx.request({
      url: ApiUrl + '/index.php?act=member_payment&op=pay_weixin',//改成你自己的链接
      data: {'openid':openid,'pay_sn':pay_sn,'key':key},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      success: function (res) {
      
        wx.requestPayment({
          'timeStamp': res.data.timeStamp.toString(),
          'nonceStr': res.data.nonceStr,
          'package': "prepay_id="+res.data.package2,
          'signType': 'MD5',
          'paySign':res.data.paySign,
          'success': function (res) {      
                  wx.showToast({
                    title: '支付成功',
                    icon: 'success',  
                    duration: 3000
                  });
          },
          'fail': function (res) {
            
              wx.showToast({
                title: '支付失败',
                icon: 'success',
                duration: 3000
              });
          },
          'complete': function (res) {
            wx.reLaunch({
              url: '/pages/order/order',
            })
                         
          }
        }); 
      },
      fail: function (res) {
        wx.showToast({
          title: '网络错误 请稍后再试~',
          icon: 'success',
          duration: 3000
        });
      }
    });
  },
})